package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("AuthorityService")
@Transactional

public class AuthorityServiceImpl extends CmiEmaService implements AuthorityService {
	public AuthorityServiceImpl() {
	}

	@Transactional
	public Authority saveAuthority(Authority authority) {
		Set<User> existingUsersForUser = new HashSet<User>();

		Set<User> selectedUsersForUser = authority.getUsersForAuthority();

		if (authority.getId() == null) {

			Authority existingAuthority = authorityDAO.findAuthorityByPhysicalPrimaryKey(authority.getName());

			if (isEquals(authority, existingAuthority)) {
				return existingAuthority;
			}

			authority = authorityDAO.store(authority);
			authorityDAO.flush();

			for (User relatedUser : selectedUsersForUser) {
				relatedUser.getAuthoritysForUser().add(authority);
				userDAO.store(relatedUser);
			}
		} else {
			Authority existingAuthority = authorityDAO.findAuthorityByPrimaryKey(authority.getId());

			existingUsersForUser = existingAuthority.getUsersForAuthority();

			Set<User> prepareDeleteUsersForUser = new HashSet<User>();
			Set<User> prepareAddUsersForUser = new HashSet<User>();

			prepareDeleteUsersForUser.addAll(selectedUsersForUser);
			prepareDeleteUsersForUser.addAll(existingUsersForUser);

			prepareAddUsersForUser.addAll(selectedUsersForUser);
			prepareAddUsersForUser.addAll(existingUsersForUser);

			prepareDeleteUsersForUser.removeAll(selectedUsersForUser);
			prepareAddUsersForUser.removeAll(existingUsersForUser);

			for (User relatedUser : prepareAddUsersForUser) {

				relatedUser.getAuthoritysForUser().add(existingAuthority);
				userDAO.store(relatedUser);
			}

			for (User relatedUser : prepareDeleteUsersForUser) {

				relatedUser.getAuthoritysForUser().remove(existingAuthority);
				userDAO.store(relatedUser);
			}
			authority = authorityDAO.store(authority);
			authorityDAO.flush();
		}

		userDAO.flush();
		return authority;
	}

	public void deleteAuthority(Authority authority) {
		authorityDAO.remove(authority);
		authorityDAO.flush();
	}

	@Transactional
	public void deleteAuthoritys(Set<Integer> deleteAuthoritysId) {
		Query query = authorityDAO.createNamedQuery("deleteAuthoritysById", -1, -1);
		query.setParameter(1, deleteAuthoritysId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Authority> loadAuthoritys() {
		return authorityDAO.findAllAuthoritys();

	}

	@Transactional
	public Set<Authority> loadReferenceAuthoritys(Set<Authority> authoritys) {
		Iterator<Authority> authoritysIterator = authoritys.iterator();
		Set<Authority> referencedAuthoritys = new HashSet<>();
		while (authoritysIterator.hasNext()) {
			Authority currentAuthority = authoritysIterator.next();

			if (!currentAuthority.getUsersForAuthority().isEmpty()) {
				referencedAuthoritys.add(currentAuthority);
				continue;
			}
		}
		return referencedAuthoritys;
	}

	public Set<Authority> loadAuthoritysByIdSet(Set<Integer> authorityIdSet) {

		Iterator<Integer> authorityIdIterator = authorityIdSet.iterator();
		Set<Authority> authoritySet = new HashSet<>();
		while (authorityIdIterator.hasNext()) {
			Integer id = authorityIdIterator.next();
			Authority currentAuthority = authorityDAO.findAuthorityById(id);
			authoritySet.add(currentAuthority);
		}
		return authoritySet;
	}

	@Transactional
	public List<Authority> findAllAuthoritys(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Authority>(authorityDAO.findAllAuthoritys(startResult, maxRows));
	}

	@Transactional
	public Authority findAuthorityByPrimaryKey(Integer id) {
		return authorityDAO.findAuthorityByPrimaryKey(id);
	}

	@Transactional
	public Integer countAuthoritys() {
		return ((Long) authorityDAO.createQuerySingleResult("select count(o) from Authority o").getSingleResult())
				.intValue();
	}

	@Transactional
	public Integer countAuthoritys(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Authority.class);
		return ((Long) authorityDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countAuthoritysByName(String queryName) {
		Query query = authorityDAO.createNamedQuery("countAuthoritysByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countAuthoritysByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Authority.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadAuthorityObjectReferencedSet(Authority authority) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> usersIds = new HashSet<Integer>();
		for (User user : authority.getUsersForAuthority()) {
			usersIds.add(user.getId());
		}
		objectReferencedSetMap.put("usersIds", usersIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadAuthorityClassReferencedSet(Authority authority) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("users", userDAO.findAllUsers());

		return classReferencedSetMap;
	}

	public boolean isEquals(Authority authority, Object obj) {
		if (obj == authority)
			return true;
		if (!(obj instanceof Authority))
			return false;
		Authority comparedAuthority = (Authority) obj;
		if (!CheckPropertyEqual(authority.getName(), comparedAuthority.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

